package com.example.base.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 23:16
 * @since JDK 1.8
 */
public class CookieUtils {


    /**
     * 根据部署路径，将cookie保存在根目录。
     *
     * @param request
     *            HttpServletRequest
     * @param response
     *            HttpServletResponse
     * @param name
     *            名称
     * @param value
     *            值
     * @param expiry
     *            过期时间 秒为单位
     * @param domain
     *            域名
     * @return
     */
    public static Cookie addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value,
                                   Integer expiry, String domain, String path) {
        Cookie cookie = new Cookie(name, value);
        if (expiry != null) {
            cookie.setMaxAge(expiry);
        }
        if (StringUtils.isNotBlank(domain)) {
            cookie.setDomain(domain);
        }
        String ctx = request.getContextPath();
        cookie.setPath(StringUtils.isBlank(ctx) ? "/" : ctx);
        if (StringUtils.isNotBlank(path)) {
            if (cookie.getPath().endsWith("/")) {
                cookie.setPath(cookie.getPath() + path);
            } else {
                cookie.setPath(cookie.getPath() + "/" + path);
            }
        }
        cookie.setHttpOnly(true);
        /**不可加上这个属性，内容、栏目预览功能需要借助cookie实现跨平台切换查看读取cookie，加上后读取不到cookie*/
        //cookie.setSecure(true);
        response.addCookie(cookie);
        return cookie;
    }


    public static Cookie getCookieByName(Cookie[] cookies,String name){
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(name)){
                return cookie;
            }
        }
        return null;
    }


}
